<template>
  <div class="message-manager">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>消息管理</h2>
      <el-tag type="info">消息中心</el-tag>
    </div>

    <div class="content-box">
      <!-- 操作栏 -->
      <el-card class="operation-area" shadow="hover">
        <div class="control-btns">
          <el-button type="primary" plain size="default" @click="refreshMessages">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
          <el-button type="danger" plain size="default" @click="markAllAsRead" :disabled="tableData.length === 0">
            <el-icon><DocumentChecked /></el-icon> 全部标记为已读
          </el-button>
        </div>
      </el-card>

      <!-- 消息列表区域 -->
      <el-card class="table-card" shadow="hover">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部消息" name="all"></el-tab-pane>
          <el-tab-pane label="系统消息" name="1"></el-tab-pane>
          <el-tab-pane label="订单消息" name="2"></el-tab-pane>
          <el-tab-pane label="客服消息" name="3"></el-tab-pane>
        </el-tabs>

        <el-table 
          ref="multipleTableRef"
          v-loading="listLoading" 
          :data="tableData" 
          tooltip-effect="dark" 
          style="width: 100%" 
          size="default"
          @selection-change="handleSelectionChange"
          border>
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
          <el-table-column prop="title" label="消息标题" min-width="200">
            <template #default="scope">
              <el-button 
                type="primary" 
                link 
                @click="viewMessageDetail(scope.row)"
                :style="{ fontWeight: scope.row.status === 0 ? 'bold' : 'normal' }">
                {{ scope.row.title }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="消息内容" min-width="250" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.content }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="消息类型" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.type === 1">系统消息</el-tag>
              <el-tag v-else-if="scope.row.type === 2" type="success">订单消息</el-tag>
              <el-tag v-else-if="scope.row.type === 3" type="warning">客服消息</el-tag>
              <el-tag v-else>其他消息</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="danger">未读</el-tag>
              <el-tag v-else type="success">已读</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发送时间" width="180" align="center"></el-table-column>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                type="primary" 
                link 
                @click="markAsRead(scope.row)" 
                :disabled="scope.row.status === 1">
                标记已读
              </el-button>
              <el-button size="small" type="danger" link @click="deleteMessage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose">
      <el-form :model="messageDetail" label-width="80px">
        <el-form-item label="消息标题">
          <el-input v-model="messageDetail.title" disabled />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input 
            v-model="messageDetail.content" 
            type="textarea" 
            :rows="4" 
            disabled />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-tag v-if="messageDetail.type === 1">系统消息</el-tag>
          <el-tag v-else-if="messageDetail.type === 2" type="success">订单消息</el-tag>
          <el-tag v-else-if="messageDetail.type === 3" type="warning">客服消息</el-tag>
          <el-tag v-else>其他消息</el-tag>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-input v-model="messageDetail.createTime" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 定义变量
const activeTab = ref('all')
const listLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('消息详情')
const tableData = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])
const messageDetail = ref({})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索参数
const listQuery = reactive({
  userId: 1, // 这里应该从用户信息中获取
  messageType: null
})

// 获取消息列表
const getMessages = () => {
  listLoading.value = true
  const params = {
    userId: listQuery.userId,
    currentPage: pagination.currentPage,
    size: pagination.pageSize
  }
  
  if (listQuery.messageType) {
    params.messageType = listQuery.messageType
  }
  
  request.get('/message/page', { params })
    .then(response => {
      if (response.data) {
        tableData.value = response.data.records
        pagination.total = response.data.total
      }
      listLoading.value = false
    })
    .catch(error => {
      console.error(error)
      ElMessage.error('获取消息列表失败')
      listLoading.value = false
    })
}

// 刷新消息
const refreshMessages = () => {
  getMessages()
}

// 标记所有为已读
const markAllAsRead = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择消息')
    return
  }
  
  const ids = multipleSelection.value.map(item => item.id)
  
  ElMessageBox.confirm('确定要将选中的消息标记为已读吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用批量标记已读的接口
    ElMessage.success('操作成功')
    getMessages()
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 标记单条消息为已读
const markAsRead = (row) => {
  request.put(`/message/read/${row.id}`)
    .then(response => {
      ElMessage.success('标记成功')
      getMessages()
    })
    .catch(error => {
      console.error(error)
      ElMessage.error('标记失败')
    })
}

// 删除消息
const deleteMessage = (row) => {
  ElMessageBox.confirm(`确定要删除消息"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除消息的接口
    ElMessage.success('删除成功')
    getMessages()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 查看消息详情
const viewMessageDetail = (row) => {
  messageDetail.value = { ...row }
  dialogVisible.value = true
  
  // 如果是未读消息，标记为已读
  if (row.status === 0) {
    markAsRead(row)
  }
}

// 处理标签页切换
const handleTabChange = (tab) => {
  if (tab === 'all') {
    listQuery.messageType = null
  } else {
    listQuery.messageType = parseInt(tab)
  }
  pagination.currentPage = 1
  getMessages()
}

// 处理多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getMessages()
}

// 处理当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getMessages()
}

// 关闭对话框
const handleClose = (done) => {
  done()
}

// 初始化
onMounted(() => {
  getMessages()
})
</script>

<style scoped>
.message-manager {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.content-box {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-btns {
  display: flex;
  gap: 10px;
}

.table-card {
  flex: 1;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
